package com.sk.weichat.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.FriendSortAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.sortlist.BaseComparator;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import de.greenrobot.event.EventBus;

/**
 * 转发 选择 好友
 */
public class SelectNewContactsActivity extends BaseActivity implements OnClickListener, ChatMessageListener {


    private PullToRefreshListView mPullToRefreshListView;
    private FriendSortAdapter mAdapter;
    private TextView mTextDialog;
    private SideBar mSideBar;
    private List<BaseSortModel<Friend>> mSortFriends;
    private BaseComparator<Friend> mBaseComparator;


    private Handler mHandler = new Handler();

    private boolean isMoreSelected;// 是否为多选转发
    private boolean isSingleOrMerge;// 逐条还是合并转发
//    private String NewUserId;
    private String fromUserId;
    private String messageId;
//    private double message_time;
    private String mLoginUserId;
    private String toUserId;

    private InstantMessageConfirm menuWindow;
    private ChatMessage mChatMessage;

    private int lvScrollPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newchat_person_selected);
        isMoreSelected = getIntent().getBooleanExtra(Constants.IS_MORE_SELECTED_INSTANT, false);
        isSingleOrMerge = getIntent().getBooleanExtra(Constants.IS_SINGLE_OR_MERGE, false);
        // 在ChatContentView内长按转发才需要以下参数
//        NewUserId = getIntent().getStringExtra("NewUserId");
        fromUserId = getIntent().getStringExtra("fromUserId");
        messageId = getIntent().getStringExtra("messageId");
//        message_time = getIntent().getDoubleExtra("message_time",0);
        mSortFriends = new ArrayList<BaseSortModel<Friend>>();
        mBaseComparator = new BaseComparator<Friend>();
        mLoginUserId = coreManager.getSelf().getUserId();

        // 添加新消息来临监听
        ListenerManager.getInstance().addChatMessageListener(this);

        initActionBar();
        initView();
        loadData();
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText("选择好友");
    }

    private void initView() {
        mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
//        View headView = View.inflate(this, R.layout.item_headview_creategroup_chat, null);
//        mPullToRefreshListView.getRefreshableView().addHeaderView(headView);
//        headView.setOnClickListener(this);

        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mAdapter = new FriendSortAdapter(this, mSortFriends);
        mAdapter.setForward(true);
        mPullToRefreshListView.getRefreshableView().setAdapter(mAdapter);
        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadData();
            }
        });

        mPullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Friend friend = mSortFriends.get((int) id).getBean();
                toUserId=friend.getUserId();
                showPopuWindow(view, friend);
            }
        });

        mTextDialog = (TextView) findViewById(R.id.text_dialog);
        mSideBar = (SideBar) findViewById(R.id.sidebar);
        mSideBar.setTextView(mTextDialog);

        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    showTextDialog(s);
                    mPullToRefreshListView.getRefreshableView().setSelection(position);
                }
            }
        });

        mPullToRefreshListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem + visibleItemCount != totalItemCount) {
                    String firstStr = mAdapter.getFirstStr(firstVisibleItem);
                    if (firstStr != null && !firstStr.equals("")) {
                        mSideBar.searchByFirstStr(firstStr);
                        if (firstVisibleItem != 0) {
                            String strLast = mAdapter.getFirstStr(firstVisibleItem - 1);
                            String strSec = mAdapter.getFirstStr(firstVisibleItem + 1);
                            if (lvScrollPosition < firstVisibleItem) {
                                if (!firstStr.equals(strLast)) {
                                    showTextDialog(firstStr);
                                }
                            } else if (lvScrollPosition > firstVisibleItem) {
                                if (!firstStr.equals(strSec)) {
                                    showTextDialog(firstStr);
                                }
                            }
                        }
                    }
                }
                lvScrollPosition = firstVisibleItem;
            }
        });
    }

    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        dialogHandler.removeMessages(0);
        dialogHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler dialogHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void showPopuWindow(View view, Friend friend) {
        menuWindow = new InstantMessageConfirm(SelectNewContactsActivity.this, new ClickListener(friend),
                friend);
        menuWindow.show();
//        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void loadData() {
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(this, ctx -> {
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            long startTime = System.currentTimeMillis();
            final List<Friend> friends = FriendDao.getInstance().getAllFriends(mLoginUserId);
            Map<String, Integer> existMap = new HashMap<>();
            List<BaseSortModel<Friend>> sortedList = SortHelper.toSortedModelList(friends, existMap, Friend::getShowName);

            long delayTime = 200 - (startTime - System.currentTimeMillis());// 保证至少200ms的刷新过程
            if (delayTime < 0) {
                delayTime = 0;
            }
            c.postDelayed(r -> {
                mSideBar.setExistMap(existMap);
                mSortFriends = sortedList;
                if (sortedList != null && sortedList.size() > 0){
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                }
                mAdapter.setData(sortedList);
                mPullToRefreshListView.onRefreshComplete();
            }, delayTime);
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.rl_headview_instant_group:
//                Intent intent = new Intent(SelectNewContactsActivity.this, SelectNewGroupInstantActivity.class);
//                intent.putExtra(Constants.IS_MORE_SELECTED_INSTANT, isMoreSelected);
//                intent.putExtra(Constants.IS_SINGLE_OR_MERGE, isSingleOrMerge);
//                intent.putExtra("fromUserId", toUserId);
//                intent.putExtra("messageId", messageId);
//                startActivity(intent);
//                finish();
//                break;
            default:
                break;
        }
    }

    /*******************************************
     * 转发&&拦截
     ******************************************/
    private void instantChatMessage(Friend friend) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //NewUserId 判断NewUserId是否为空  如果为空则是通过一般的聊天记录转发，NewUserId不需管  如果不为空则是通过web页转发，需要通过NewUserId查找ChatMessage

                mChatMessage = ChatMessageDao.getInstance().findMsgById(mLoginUserId, fromUserId, messageId);
                mChatMessage.setFromUserId(mLoginUserId);
                mChatMessage.setFromUserName(coreManager.getSelf().getNickName());
                mChatMessage.setToUserId(friend.getUserId());
                mChatMessage.setUpload(true);
                mChatMessage.setMySend(true);
                mChatMessage.setReSendCount(5);
                mChatMessage.setSendRead(false);
                // 因为该消息的原主人可能开启了消息传输加密，我们对于content字段解密后存入了数据库，但是isEncrypt字段并未改变
                // 如果我们将此消息转发给另一人，对方可能会对我方已解密的消息再次进行解密
                mChatMessage.setIsEncrypt(0);
                mChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                mChatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));

                //未回复消息，即打招呼消息
                if(friend.getReplyStatus()==Friend.STATUS_REPLAY_NONE){
                    if ( mChatMessage.getType() == XmppMessage.TYPE_IMAGE
                            || mChatMessage.getType() == XmppMessage.TYPE_VIDEO || mChatMessage.getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送

                        mChatMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                    }
                }
                //非好友不能发语音
                if(friend.getStatus()!=Friend.STATUS_FRIEND &&friend.getStatus()!=Friend.STATUS_SYSTEM && mChatMessage.getType() == XmppMessage.TYPE_VOICE){
                    mChatMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                }
                ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, friend.getUserId(), mChatMessage);


                coreManager.sendChatMessage(friend.getUserId(), mChatMessage);

                if(friend.getStatus()!=Friend.STATUS_FRIEND&&friend.getStatus()!=Friend.STATUS_SYSTEM
                        &&friend.getReplyStatus()==Friend.STATUS_REPLAY_NONE){//未回复消息，即打招呼消息
                    if (mChatMessage.getType() == XmppMessage.TYPE_IMAGE
                            || mChatMessage.getType() == XmppMessage.TYPE_VIDEO || mChatMessage.getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送
                        String content="";
                        switch (mChatMessage.getType()){

                            case XmppMessage.TYPE_IMAGE:
                                content="图片发送失败，对方回复后才能使用图片功能";
                                break;
                            case XmppMessage.TYPE_VIDEO:
                                content="视频发送失败，对方回复后才能使用视频功能";
                                break;
                            case XmppMessage.TYPE_FILE:
                                content="文件发送失败，对方回复后才能使用文件功能";
                                break;
                        }

                        //本地添加一个系统提示信息
                        FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, mChatMessage.getToUserId(),content);
                        Intent intent = new Intent();
                        intent.putExtra("toUserId",toUserId);
                        setResult(InstantMessageActivity.RESULT_SELECT_SUCCESS,intent);
                        finish();
                        return;
                    }else{
                        mChatMessage.setMsgType(ChatMessage.TYPE_HELLO);
                    }
                }else  if(friend.getStatus()!=Friend.STATUS_FRIEND && friend.getStatus()!=Friend.STATUS_SYSTEM
                        &&friend.getReplyStatus()==Friend.STATUS_REPLAY_SINGLE){//对方已经单方面发送了打招呼消息
                    mChatMessage.setMsgType(ChatMessage.TYPE_HELLO);
                }

                //非好友不能发送语音消息
                if(friend.getStatus()!=Friend.STATUS_FRIEND && friend.getStatus()!=Friend.STATUS_SYSTEM){
                    if (mChatMessage.getType() == XmppMessage.TYPE_VOICE){
                        String content="互为好友才能发送语音";
                        //本地添加一个系统提示信息
                        FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, mChatMessage.getToUserId(),content);
                        Intent intent = new Intent();
                        intent.putExtra("toUserId",toUserId);
                        setResult(InstantMessageActivity.RESULT_SELECT_SUCCESS,intent);
                        finish();
                        return;
                    }
                }
            }
        }, 1000);
    }

    /**
     * 消息监听
     * @param messageState
     * @param msgId
     */
    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {

        if (TextUtils.isEmpty(msgId)) {
            return;
        }
        if (mChatMessage!=null && msgId.equals(mChatMessage.getPacketId())) {
            /**
             * 之前发现对方已经收到消息了，这里还在转圈，退出重进之后又变为送达了，
             * 调试时发现出现该问题是因为消息状态先更新的1，在更新的0，这里处理下
             */
            if (messageState == 1||messageState==ChatMessageListener.MESSAGE_SEND_OVER) {
                //ToastUtil.showToast(getApplicationContext(),"转发成功");
                Intent intent = new Intent();
                intent.putExtra("toUserId",toUserId);
                setResult(InstantMessageActivity.RESULT_SELECT_SUCCESS,intent);
                finish();

            }else if(messageState == 2){
                ToastUtil.showToast(getApplicationContext(),"转发失败");
            }

        }
    }

    @Override
    public boolean onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        return false;
    }

    /**
     * 事件的监听
     */
    class ClickListener implements OnClickListener {
        private Friend friend;

        public ClickListener(Friend friend) {
            this.friend = friend;
        }

        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_send:
                    if (isMoreSelected) {// 多选转发 通知多选页面(即多选消息的单聊 || 群聊页面，在该页面获取选中的消息在发送出去)
                        EventBus.getDefault().post(new EventMoreSelected(friend.getUserId(), isSingleOrMerge, false));
                        Intent intent = new Intent();
                        intent.putExtra("toUserId",toUserId);
                        setResult(InstantMessageActivity.RESULT_SELECT_SUCCESS,intent);
                        finish();
                    } else {
//                        Intent intent = new Intent(SelectNewContactsActivity.this, ChatActivity.class);
//                        intent.putExtra(ChatActivity.FRIEND, friend);
//                        intent.putExtra("fromUserId", toUserId);
//                        intent.putExtra("messageId", messageId);
//                        startActivity(intent);
//                        finish();
                        instantChatMessage(friend);
                    }
                    break;
                case R.id.btn_cancle:// 取消
                    break;
                default:
                    break;
            }
        }
    }
}
